/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.teach.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lczyfz.istep.common.mapper.JsonMapper;
import com.lczyfz.istep.modules.resource.entity.ResourceCourse;
import com.lczyfz.istep.modules.sys.service.SystemService;
import com.lczyfz.istep.modules.teach.entity.TeachStudent;
import com.lczyfz.istep.modules.teach.entity.TeachTeacher;
import com.lczyfz.istep.modules.teach.service.TeachStudentService;
import com.lczyfz.istep.modules.teach.service.TeachTeacherService;
import com.lczyfz.istep.modules.teach.service.TeachTeacherService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.web.BaseController;
import com.lczyfz.istep.common.utils.StringUtils;
import com.lczyfz.istep.modules.teach.entity.TeachClass;
import com.lczyfz.istep.modules.teach.service.TeachClassService;
import com.lczyfz.istep.modules.teach.service.TeachTeacherService;

import java.util.List;

/**
 * 班级管理Controller
 * @author cqh
 * @version 2017-01-12
 */
@Controller
@RequestMapping(value = "${adminPath}/teach/teachClass")
public class TeachClassController extends BaseController {

	@Autowired
	private TeachClassService teachClassService;
	@Autowired
	private TeachStudentService teachStudentService;
//	@Autowired
//	private TeachTeacherService teachTeacherService;
	@Autowired
	private SystemService systemService;

	@ModelAttribute
	public TeachClass get(@RequestParam(required=false) String id) {
		TeachClass entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = teachClassService.get(id);
		}
		if (entity == null){
			entity = new TeachClass();
		}
		return entity;
	}



	//	AlisaYe
	//班级管理列表展示
	@RequiresPermissions("teach:teachClass:view")
	@RequestMapping(value = {"list", ""})
	public String list(TeachClass teachClass, HttpServletRequest request, HttpServletResponse response, Model model) {
		String getTeacherName;
		Page<TeachClass> page = teachClassService.findPage(new Page<TeachClass>(request, response), teachClass);
		for(int i=0;i<page.getList().size();i++){
			if(page.getList().get(i).getUserId().equals("0")){//
				getTeacherName="";//
			}
			else if(page.getList().get(i).getUserId()==null){
				getTeacherName="";
			}
			else {

				TeachStudent teachstudent=teachStudentService.get(page.getList().get(i).getUserId());
//				String aa=page.getList().get(i).getUserId();
//				TeachStudent teachstudent0=teachStudentService.get("01fdb1387d4f45e8acecc225915eb296");
				//这里的- 002=Alisa==teachClass==null
//				logger.debug("002=Alisa==teachClass=="+teachstudent);
//				logger.debug("002=Alisa==teachClass==teachstudent0=="+teachstudent0);
//				logger.debug("002=Alisa==teachClass==aa=="+aa);
				if(teachstudent!=null) {
					getTeacherName = teachstudent.getName();
				}
				else{
					getTeacherName="";
				}

//				logger.debug("0022=Alisa==teachClass=="+getTeacherName);
			}

				page.getList().get(i).setUserId(getTeacherName);


		}
		//条件查询下拉框
		List<TeachTeacher> allTeacherList = teachClassService.findAllTeacherList( );
		logger.debug("003--AlisaYe==allTeacherList=="+allTeacherList);
		model.addAttribute("allTeacherList", allTeacherList);

		model.addAttribute("page", page);
		return "modules/teach/teachClassList";
	}



/*
	//	AlisaYe
	//班级管理列表展示
	@RequiresPermissions("teach:teachClass:view")
	@RequestMapping(value = {"list", ""})
	public String list(TeachClass teachClass, HttpServletRequest request, HttpServletResponse response, Model model) {

		Page<TeachClass> page = teachClassService.findPage(new Page<TeachClass>(request, response), teachClass);

		//条件查询下拉框
		List<TeachTeacher> allTeacherList = teachClassService.findAllTeacherList( );
		logger.debug("--AlisaYe==allTeacherList=="+allTeacherList);
		model.addAttribute("allTeacherList", allTeacherList);

		model.addAttribute("page", page);
		return "modules/teach/teachClassList";
	}
	*/



//	//原班级管理列表展示
//	@RequiresPermissions("teach:teachClass:view")
//	@RequestMapping(value = {"list", ""})
//	public String list(TeachClass teachClass, HttpServletRequest request, HttpServletResponse response, Model model) {
//		Page<TeachClass> page = teachClassService.findPage(new Page<TeachClass>(request, response), teachClass);
//		model.addAttribute("page", page);
//		return "modules/teach/teachClassList";
//	}



	//	AlisaYe
	//班级添加展示
	@RequiresPermissions("teach:teachClass:view")
	@RequestMapping(value = "form")
	public String form(TeachClass teachClass, Model model) {
		List<TeachTeacher> allTeacherList = teachClassService.findAllTeacherList();
//		logger.debug("=AlisaYe=allTeacherList111=="+allTeacherList);
		model.addAttribute("allTeacherList", allTeacherList);
		model.addAttribute("teachClass", teachClass);
		return "modules/teach/teachClassForm";
	}

//
//	@RequiresPermissions("teach:teachClass:view")
//	@RequestMapping(value = "form")
//	public String form(TeachClass teachClass, Model model) {
//		model.addAttribute("teachClass", teachClass);
//		return "modules/teach/teachClassForm";
//	}
//


	//AlisaYe
	//班级管理添加
	@RequiresPermissions("teach:teachClass:edit")
	@RequestMapping(value = "save")
	public String save(TeachClass teachClass, Model model, RedirectAttributes redirectAttributes) {

//		logger.debug("==AlisaYe====insert==teach_class==c000="+teachClass.getUserId()+","+teachClass.getClassName()+","+teachClass.getRemarks());
		if (!beanValidator(model, teachClass)){
			return form(teachClass, model);
		}

		//AlisaYe还需要做一个班级名是否存在的判断。
		if ("false".equals(checkClassName(teachClass.getOldClassName(), teachClass.getClassName()))) {
			addMessage(model, "保存班级'" + teachClass.getClassName() + "'失败，班级名已经存在");
			return form(teachClass, model);
		}
		teachClassService.save(teachClass);
//		teachClassService.saveClass(teachClass);
//		logger.debug("==AlisaYe====insert==teach_class==c111="+teachClass.getUserId()+","+teachClass.getClassName()+","+teachClass.getRemarks());
		addMessage(redirectAttributes, "保存班级：'" + teachClass.getClassName() + "'成功");
		return "redirect:"+Global.getAdminPath()+"/teach/teachClass/?repage";
	}

	//原始
//	@RequiresPermissions("teach:teachClass:edit")
//	@RequestMapping(value = "save")
//	public String save(TeachClass teachClass, Model model, RedirectAttributes redirectAttributes) {
//		if (!beanValidator(model, teachClass)){
//			return form(teachClass, model);
//		}
//		teachClassService.save(teachClass);
//		addMessage(redirectAttributes, "保存班级管理成功");
//		return "redirect:"+Global.getAdminPath()+"/teach/teachClass/?repage";
//	}

	//AlisaYe
	//班级管理详情页面




	@RequiresPermissions("teach:teachClass:edit")
	@RequestMapping(value = "delete")
	public String delete(TeachClass teachClass, RedirectAttributes redirectAttributes) {
		//		AlisaYe  2017/03/13
		//设置被删除的班级的学生的班级Id为0
//		List<TeachStudent> studentClassIDonDeleteClass=teachClassService.studentClassIDonDeleteClassList();
//		logger.debug("====AlisaYe===studentClassIDonDeleteClass=== [{}]",studentClassIDonDeleteClass);
//		logger.debug("====AlisaYe===studentClassIDonDeleteClass.getclassid()=== [{}]",teachClass.getId());
//		logger.debug("====AlisaYe===studentClassIDonDeleteClass.size()=== [{}]",studentClassIDonDeleteClass.size());
//		for(int i=0;i<studentClassIDonDeleteClass.size();i++)
//		{
//			logger.debug("====AlisaYe===studentClassIDonDeleteClass.size()=studentid== [{}]",studentClassIDonDeleteClass.get(i).getId());
//			logger.debug("====AlisaYe===studentClassIDonDeleteClass.size()=studentname== [{}]",studentClassIDonDeleteClass.get(i).getName());
//			studentClassIDonDeleteClass.get(i).setClassId("0");
//			teachStudentService.save(studentClassIDonDeleteClass.get(i));
//		}

		teachClassService.delete(teachClass);
		addMessage(redirectAttributes, "删除班级：'" + teachClass.getClassName() + "'成功");
		return "redirect:"+Global.getAdminPath()+"/teach/teachClass/?repage";
	}


	/**
	 * AlisaYe 2017/03/06
	 * *AlisaYe 2017/03/09
	 * 复制修改班级页面跳转
	 */
//	@RequiresPermissions("teach:teachClass:view")//Alisa0310
//	@RequestMapping(value = "copyClassForm")
//	public String copyClassForm(Model model) {
//		//显示班级名称-副本
//		//显示所有教师列表!
//		//显示所有非本班学生和本班学生列表
//		//参照TeachStudentController.batchAddForm()
//		List<TeachTeacher> allTeacherList = teachClassService.findAllTeacherList();
//		List<TeachTeacher> allOtherAddStudentList = teachClassService.allOtherAddStudentList();
//		model.addAttribute("allTeacherList", allTeacherList);
//		model.addAttribute("allOtherAddStudentList", allOtherAddStudentList);
//		return "modules/teach/teachClassCopyForm";
//	}


	@RequiresPermissions("teach:teachClass:view")//Alisa0310
	@RequestMapping(value = "copyClassForm")
	public String copyClassForm(TeachClass teachClass,Model model,String type) {
//		logger.debug("====AlisaYe===teachClass=== [{}]",teachClass);
		TeachStudent teachStudent=new TeachStudent();
		String className00=teachClass.getClassName();
//		logger.debug("====AlisaYe===className00className00className00className00className00className00=[{}]", className00);
		List<TeachStudent> allStudentList=teachStudentService.findAllStudentList();
		int count=0;
		if(teachClass!=null&&teachClass.getId()!=null&&!teachClass.getId().equals("")) {
			List<TeachStudent> findAllStudentByClassId=teachClassService.findAllStudentByClassId(teachClass.getId());
//			logger.debug("====AlisaYe===班级id [{}]", teachClass.getId());
			for (int i = 0; i < allStudentList.size(); i++) {
				if(allStudentList.size()==0)
				{
					break;
				}
				else {
					for(int j=0;j<findAllStudentByClassId.size();j++){
//						logger.debug("====AlisaYe===findAllStudentByClassId,size=[{}]===[{}]", findAllStudentByClassId.size(),findAllStudentByClassId.get(j).getId());
						if(allStudentList.get(i).getId().equals(findAllStudentByClassId.get(j).getId()))
						{
//							logger.debug("====AlisaYe===chooseded=[{}]===[{}]", findAllStudentByClassId.get(j).getId(),allStudentList.get(i).getName());
							allStudentList.get(i).setIsChoose("true");
							count++;
//							findAllStudentByClassId.remove(j);
							break;
						}
					}
				}

			}
		}
//		logger.debug("====AlisaYe===size=size=size=size=== [{}]",allStudentList.size());
		if(type!=null&&type.equals("copy"))
		{
			teachClass.setClassName(teachClass.getClassName() + "_副本");
//			logger.debug("===AlisaYe===ClassName[{}]", teachClass.getClassName());
		}
		if(systemService.isSuperAdmin())
		{
			model.addAttribute("isSuperAdmin", "true");
		}else
			model.addAttribute("isSuperAdmin", "false");


		List<TeachTeacher> allTeacherList = teachClassService.findAllTeacherList();
//		List<TeachTeacher> allOtherAddStudentList = teachClassService.allOtherAddStudentList();
//		List<TeachStudent> allBatchAddStudentList = teachStudentService.findAllBatchAddStudentList();
		model.addAttribute("className00", className00);
		model.addAttribute("type", type);
		model.addAttribute("allTeacherList", allTeacherList);
//		model.addAttribute("allBatchAddStudentList", allBatchAddStudentList);
		model.addAttribute("allStudentList", allStudentList);
		return "modules/teach/teachClassCopyForm";
	}


	/**
	 * AlisaYe 2017/03/06
	 * * AlisaYe 2017/03/09
	 * 复制修改班级页面学生添加
	 *
	 */
//	version1.0
//	@RequestMapping(value = "copyClass")
//	public String copyClass(String classId, String duallist, RedirectAttributes redirectAttributes) {
//		logger.debug("=Alisa==duallist=="+duallist);
//		String[] allOtherAddStudentList = duallist.split(",");
////		for (int i = 0; i < allOtherAddStudentList.length; i++) {
//		for (String anllOtherAddStudentList : allOtherAddStudentList) {
//			TeachStudent teachStudent = teachStudentService.get(anllOtherAddStudentList);
//			teachStudent.setClassId(classId);
//			teachStudentService.update(teachStudent);
//		}
//		addMessage(redirectAttributes, "复制班级成功");
//		return "redirect:" + Global.getAdminPath() + "/teach/teachClass/list/?repage";
//	}

	@RequiresPermissions("teach:teachClass:view")//Alisa0310
	@RequestMapping(value = "copyClass")
	public String copyClass(TeachClass teachClass, String duallist, RedirectAttributes redirectAttributes,String type, Model model,String className00) {
		if (!beanValidator(model, teachClass)){
			return copyClassForm(teachClass,model, type);
		}
//		logger.debug("=Alisa============================================================================================");
//		logger.debug("=Alisa==duallist000=="+duallist);
//		logger.debug("=Alisa==teachClass=="+teachClass);
//		logger.debug("remarks: [{}]", teachClass.getRemarks());
//		logger.debug("classname: [{}]", teachClass.getClassName());
//		logger.debug("userid: [{}]", teachClass.getUserId());
//		logger.debug("type: [{}]", type);
//		logger.debug("=Alisa============================================================================================");
		if(type!=null&&type.equals("copy"))
		{
//			logger.debug("===AlisaYe===开始复制班级！=============");

			if ("false".equals(checkClassName(teachClass.getOldClassName(), teachClass.getClassName())))
			{
				//这个提示的效果好像不是很明显哦！跳转的很快！~
				addMessage(redirectAttributes,  "'失败，班级名已经存在");
				return copyClassForm(teachClass, model, type);
			}
			else
			{
				TeachClass tempClass=new TeachClass();
				tempClass.setClassName(teachClass.getClassName());
				tempClass.setUserId(teachClass.getUserId());
				tempClass.setRemarks(teachClass.getRemarks());
				teachClassService.save(tempClass);

				String[] allStudentList = duallist.split(",");
				//设置被选中的班级是该班级。
				for (String aStudentList : allStudentList) {
					TeachStudent teachStudent = teachStudentService.get(aStudentList);
//					logger.debug("======AlisaYe========teachStudent: [{}]", teachStudent);
					//在teach_class_student表中新增一个记录才对哦！~
					teachClassService.insertTeachClassStudent(tempClass.getId(),teachStudent.getId());
//					teachStudentService.update(teachStudent);
				}
			}
			addMessage(redirectAttributes, "复制班级成功");
		}
		else{
//			logger.debug("===AlisaYe===开始修改班级！================");
			//					在执行insert之前需要把属于该班的学生的信息删除。
			//修改班级的时候，原始班级信息要清空再处理一遍。2017/03/22

					teachClass.setClassName(teachClass.getClassName());
				//如果班级名字没有被修改
				if(className00.equals(teachClass.getClassName()))
				{
//					logger.debug("===AlisaYe===同名原来的classname！================");
//					teachClass.setClassName(teachClass.getClassName());
					teachClass.setUserId(teachClass.getUserId());
					teachClass.setRemarks(teachClass.getRemarks());
					teachClassService.save(teachClass);

					String[] allStudentList = duallist.split(",");
					//设置被选中的班级是该班级。

//					删除属于该班级的学生信息，再重新添加
					teachClassService.deleteClassStudentModify(teachClass.getId());
					for (String aStudentList : allStudentList) {
						TeachStudent teachStudent = teachStudentService.get(aStudentList);
//						logger.debug("======AlisaYe========teachStudent: [{}]", teachStudent);
						//此处的修改需要将该班级在teach_class_student表中的该班记录删去
						teachClassService.insertTeachClassStudent(teachClass.getId(),teachStudent.getId());
//						teachStudent.setClassId(teachClass.getId());
//						teachStudentService.update(teachStudent);
					}

				}else
				{
				//如果班级名字被修改，看看是不是同名。
					if ("false".equals(checkClassName(teachClass.getOldClassName(), teachClass.getClassName())))
					{
//						logger.debug("===AlisaYe===同名列表中的classname！================");
						//这个提示的效果好像不是很明显哦！跳转的很快！~
						addMessage(redirectAttributes,  "'失败，班级名已经存在");
//						addMessage(model, "保存班级'" + teachClass.getClassName() + "'失败，班级名已经存在");
//						return "modules/teach/teachClassList";
//						return form(teachClass, model);
						teachClass.setClassName(className00);
						return copyClassForm(teachClass, model, type);
					}
//					teachClass.setClassName(teachClass.getClassName());
					teachClass.setUserId(teachClass.getUserId());
					teachClass.setRemarks(teachClass.getRemarks());
					teachClassService.save(teachClass);

					String[] allStudentList = duallist.split(",");
					//设置被选中的班级是该班级。
					teachClassService.deleteClassStudentModify(teachClass.getId());
					for (String aStudentList : allStudentList) {
						TeachStudent teachStudent = teachStudentService.get(aStudentList);
//						logger.debug("======AlisaYe========teachStudent: [{}]", teachStudent);
//						teachStudent.setClassId(teachClass.getId());
						teachClassService.insertTeachClassStudent(teachClass.getId(),teachStudent.getId());
//						teachStudentService.update(teachStudent);

					}
				}


//				String[] allStudentList = duallist.split(",");
//				//设置被选中的班级是该班级。
//				for (String aStudentList : allStudentList) {
//					TeachStudent teachStudent = teachStudentService.get(aStudentList);
//					logger.debug("======AlisaYe========teachStudent: [{}]", teachStudent);
//					teachStudent.setClassId(teachClass.getId());
//					teachStudentService.update(teachStudent);
//				}


//
			addMessage(redirectAttributes, "修改班级成功");

		}


//		logger.debug("=Alisa==duallist111=="+duallist);

		return "redirect:" + Global.getAdminPath() + "/teach/teachClass/list/?repage";
	}




	/**
	 * AlisaYe 2017/03/06
	 * @param teachClass
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * 查看班级详情
	 * 显示该班级的所有学生
	 */
	@RequiresPermissions("teach:teachClass:view")
	@RequestMapping(value = "detail")
	public String detail(TeachClass teachClass, Model model, HttpServletRequest request, HttpServletResponse response,String teacherName) {


//		logger.debug("==AlisaYe==teachClass=== [{}]", teachClass);
		TeachStudent teacherStudent=new TeachStudent();
		teacherStudent.setClassId(teachClass.getId());

		teachClass.setUserId(teacherName);
//		logger.debug("==AlisaYe==classId=== [{}]", teacherStudent.getClassId());
//		logger.debug("==AlisaYe==getId=== [{}]", teacherStudent.getId());

		Page<TeachStudent> page =teachStudentService.findPageByClassId(new Page<TeachStudent>(request, response), teacherStudent);
//		logger.debug("page.getList().size()=== [{}]", page.getList().size());

		model.addAttribute("page", page);
		model.addAttribute("teachClass", teachClass);
		return "modules/teach/teachClassDetail";
	}







	//验证班级名称是否有效,false时，说明登录名已经存在
	@ResponseBody
	@RequiresPermissions("teach:teachClass:edit")
	@RequestMapping(value = "checkClassName")
	public String checkClassName(String oldClassName,String className) {
//		logger.debug("=Alisa===className==="+oldClassName+","+className);
		if (className != null && className.equals(oldClassName)) {
//			logger.debug("=Alisa===修改班级==="+oldClassName+","+className);
			return "true";
		} else if(className != null && teachClassService.findClassByClassName(className) == null){
//			logger.debug("=Alisa===添加班级==="+oldClassName+","+className);
			return "true";
		}
		return "false";
	}




}